<?php

namespace Sys\Helper;
/**
 * 微信辅助类
 * User: Administrator
 * Date: 2018/1/25
 * Time: 10:03
 */
class WeiXinHelper
{
    private $appId = '';
    private $secret = '';
    private $code = '';

    /**
     * 设置参数
     * @param $app_id
     * @param $app_secret
     * @param $code
     */
    public function __construct($app_id, $app_secret, $code)
    {
        $this->appId  = $app_id;
        $this->secret = $app_secret;
        $this->code   = $code;
    }

    /**
     * 获取openid
     * @return bool
     */
    public function getOpenid()
    {
        $url_format = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code';
        $url        = sprintf($url_format, $this->appId, $this->secret, $this->code);

        $data = $this->curlRequest($url);
        if (isset($data['openid'])) {
            return $data['openid'];
        } else {
            $openid = $this->refreshAccessToken();
            if ($openid) {
                return $openid;
            }
        }
        return false;
    }

    /**
     * 获取用户信息
     * @return bool|mixed
     */
    public function getOpenInfo()
    {
        $url_format = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code';
        $url        = sprintf($url_format, $this->appId, $this->secret, $this->code);

        $data = $this->curlRequest($url);
        if ($data) {
            return $data;
        }
        return false;
    }

    /**
     * 刷新accessToken
     * @return bool
     */
    public function refreshAccessToken()
    {
        $url_format = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=REFRESH_TOKEN';
        $url        = sprintf($url_format, $this->appId);
        $data       = $this->curlRequest($url);
        if (isset($data['openid'])) {
            return $data['openid'];
        }
        return false;
    }

    /**
     * 检查,回调code
     */
    public static function check()
    {
        if (self::checkWeiXin()) {
            $is = isset($_GET['is']) ? intval($_GET['is']) : 0;
            if (!isset($_COOKIE['openid']) || $is == 200) {
                $openid = config('wx.appid');
                $redirect = urlencode(config('wx.redirect_url'));
                $scope = 'snsapi_userinfo';//snsapi_base
                $url_format = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=zm#wechat_redirect';
                $url = sprintf($url_format, $openid, $redirect, $scope);
                header("Location:{$url}");
            }
        }
    }

    /**
     * 检查是否是微信环境
     * @return bool
     */
    public static function checkWeiXin()
    {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($user_agent, 'MicroMessenger') === false) {
            //echo '非微信浏览器禁止浏览';
            return false;
        } else {
            return true;
        }
    }

    /**
     * 请求curl
     * @param $url
     * @return bool|mixed
     */
    public function curlRequest($url)
    {
        //初始化curl
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //运行curl，结果以jason形式返回
        $res = curl_exec($ch);
        curl_close($ch);
        if (!json_decode($res)) {
            return false;
        }
        $data = json_decode($res, true);
        return $data;
    }
}